//
//  ToggleButtonIntent.swift
//  TomatoClock
//
//  Created by DaleGuo on 2023/10/31.
//

import AppIntents
import Foundation
import SwiftUI
import WidgetKit
import ActivityKit

// LiveActivityIntent 替换掉 appIntent。 The intent needs to conform to this protocol to be allowed to start a Live Activity by the system. The Live Activity must be created, and started, manually by the intent.
struct ToggleButtonIntent: LiveActivityIntent {
    static var title: LocalizedStringResource = "ToggleButtonIntent"
    
    @MainActor
    func perform() async throws -> some IntentResult {
        let notificationHelper = NotificationHandler.Notification
//
        let defalult = UserDefaults(suiteName: "group.com.dale.tomato_clock")!
//
        var is_starting = defalult.bool(forKey: "is_starting")
//
        is_starting.toggle()
//
        // 更改 start状态
        defalult.set(is_starting, forKey: "is_starting")
        
        let tomatoDate_string = defalult.object(forKey: "tomatoDate")!

        let tomatoDate = Date(timeIntervalSinceReferenceDate: Double(tomatoDate_string as! String) ?? 0.0)
//        print(tomatoDate)
        
        let sliderValue = defalult.double(forKey: "sliderValue")
        
        // 存放都用String
        defalult.setValue(Date().addingTimeInterval(sliderValue * 60).timeIntervalSinceReferenceDate.description, forKey: "tomatoDate")
        
        
        
        
//        设置通知
        if is_starting {
            notificationHelper.sendTomatoNotification(tomatoDate: tomatoDate)
            ActivityWidgetUtil.startActivity(tomatoDate: tomatoDate)
            
        } else {
            notificationHelper.cancelNotification()
            ActivityWidgetUtil.stopActivity()
        }
        
        return .result()
    }
    
    
    
    
    
}
